package org.dromara.system.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.oss.core.OssClient;
import org.dromara.common.oss.factory.OssFactory;
import org.dromara.system.domain.SysSolutionDoc;
import org.dromara.system.domain.bo.SysSolutionDocBo;
import org.dromara.system.domain.vo.SysSolutionDocVo;
import org.dromara.system.mapper.SysSolutionDocMapper;
import org.dromara.system.service.ISysSolutionDocService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.List;

/**
 * 解决方案文档Service业务层处理
 *
 * @author system
 */
@RequiredArgsConstructor
@Service
public class SysSolutionDocServiceImpl implements ISysSolutionDocService {

    private final SysSolutionDocMapper baseMapper;

    /**
     * 查询解决方案文档列表
     *
     * @param queryBo   查询参数
     * @param pageQuery 分页参数
     * @return 解决方案文档分页列表
     */
    @Override
    public TableDataInfo<SysSolutionDocVo> queryPageList(SysSolutionDocBo queryBo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysSolutionDoc> lqw = buildQueryWrapper(queryBo);
        Page<SysSolutionDocVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    private LambdaQueryWrapper<SysSolutionDoc> buildQueryWrapper(SysSolutionDocBo queryBo) {
        LambdaQueryWrapper<SysSolutionDoc> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(queryBo.getDocName()), SysSolutionDoc::getDocName, queryBo.getDocName());
        // 仅按名称模糊查询
        lqw.orderByDesc(SysSolutionDoc::getCreateTime);
        return lqw;
    }

    /**
     * 查询解决方案文档详情
     *
     * @param docId 文档ID
     * @return 解决方案文档详情
     */
    @Override
    public SysSolutionDocVo queryById(Long docId) {
        SysSolutionDoc entity = baseMapper.selectById(docId);
        return MapstructUtils.convert(entity, SysSolutionDocVo.class);
    }


    /**
     * 上传PDF文件夹格式解决方案
     */
    @Override
    public SysSolutionDocVo uploadPdfFolderSolution(MultipartFile[] files, String folderName, String remark) {
        if (files == null || files.length == 0) {
            throw new ServiceException("文件夹不能为空");
        }

        // 识别主PDF文件（基础文件名以 -main 结尾，且扩展名为 .pdf）
        String mainFileName = null;

        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            if (StringUtils.isNotBlank(fileName)) {
                String lower = fileName.toLowerCase();
                int dotIdx = lower.lastIndexOf('.');
                String baseName = dotIdx > 0 ? lower.substring(0, dotIdx) : lower;
                boolean isPdf = lower.endsWith(".pdf");
                boolean baseEndsWithMain = baseName.endsWith("-main");
                if (isPdf && baseEndsWithMain) { mainFileName = fileName; break; }
            }
        }

        if (StringUtils.isBlank(mainFileName)) {
            throw new ServiceException("未找到主PDF文件（基础文件名以 -main 结尾，且扩展名为 .pdf）");
        }

        try {
            // 兜底方案名：若未传 folderName，则使用主文件名去掉 ".pdf" 与末尾 "-main" 作为方案名
            String resolvedFolderName = folderName;
            if (StringUtils.isBlank(resolvedFolderName)) {
                String mf = mainFileName;
                int dot = mf.lastIndexOf('.');
                String base = dot > 0 ? mf.substring(0, dot) : mf;
                if (base.endsWith("-main")) {
                    base = base.substring(0, base.length() - 5);
                }
                resolvedFolderName = StringUtils.isNotBlank(base) ? base : "solution";
            }

            // 生成唯一的文件夹路径
            String uniqueFolderPath = "pdf-solutions/" + resolvedFolderName + "-" + IdUtil.simpleUUID() + "/";

            OssClient ossClient = OssFactory.instance();
            String mainFileUrl = null;
            int totalFileCount = 0;

            for (MultipartFile file : files) {
                String originalFileName = file.getOriginalFilename();
                if (StringUtils.isBlank(originalFileName)) {
                    continue;
                }

                String fileKey = uniqueFolderPath + originalFileName;
                ossClient.upload(file.getInputStream(), fileKey, file.getSize(), file.getContentType());
                totalFileCount++;

                if (mainFileName.equals(originalFileName)) {
                    mainFileUrl = ossClient.getUrl() + "/" + fileKey;
                }
            }

            if (StringUtils.isBlank(mainFileUrl)) {
                throw new ServiceException("主文件上传失败");
            }

            SysSolutionDoc solutionDoc = new SysSolutionDoc();
            solutionDoc.setDocName(resolvedFolderName);
            solutionDoc.setDocUrl(mainFileUrl);
            solutionDoc.setMainFileName(mainFileName);
            // PDF方案不需要资源文件夹
            // 无资源文件夹
            solutionDoc.setFolderPath(uniqueFolderPath);
            solutionDoc.setTotalFiles(totalFileCount);
            solutionDoc.setRemark(remark);

            baseMapper.insert(solutionDoc);

            return MapstructUtils.convert(solutionDoc, SysSolutionDocVo.class);

        } catch (Exception e) {
            throw new ServiceException("PDF文件夹上传失败: " + e.getMessage());
        }
    }

    /**
     * 修改解决方案文档
     *
     * @param bo 解决方案文档
     * @return 结果
     */
    @Override
    public Boolean updateByBo(SysSolutionDocBo bo) {
        SysSolutionDoc update = new SysSolutionDoc();
        update.setDocId(bo.getDocId());
        update.setDocName(bo.getDocName());
        update.setDocUrl(bo.getDocUrl());
        update.setMainFileName(bo.getMainFileName());
        update.setFolderPath(bo.getFolderPath());
        update.setTotalFiles(bo.getTotalFiles());
        update.setRemark(bo.getRemark());
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysSolutionDoc entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除解决方案文档
     *
     * @param ids 需要删除的解决方案文档主键
     * @return 结果
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        List<SysSolutionDoc> list = baseMapper.selectByIds(ids);
        for (SysSolutionDoc solutionDoc : list) {
            // 删除方案文件夹
            if (StringUtils.isNotBlank(solutionDoc.getFolderPath())) {
                try {
                    OssClient ossClient = OssFactory.instance();
                    // 删除整个文件夹（需要先列出文件夹下所有文件再逐个删除）
                    // 注意：这里简化处理，实际可能需要根据具体OSS实现调整
                    ossClient.delete(solutionDoc.getFolderPath());
                } catch (Exception e) {
                    // 记录日志但不阻止删除操作
                    // log.warn("删除OSS文件夹失败: {}", solutionDoc.getFolderPath(), e);
                }
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 预览或下载解决方案文档
     *
     * @param docId       文档ID
     * @param disposition 显示方式：inline-预览，attachment-下载
     * @param response    响应对象
     */
    @Override
    public void previewDocument(Long docId, String disposition, HttpServletResponse response) throws Exception {
        SysSolutionDoc solutionDoc = baseMapper.selectById(docId);
        if (solutionDoc == null) {
            throw new ServiceException("文档不存在");
        }

        // 方案B：使用用户端匿名文件路由，便于预览且保持相对链接可用
        String mainName = solutionDoc.getMainFileName();
        String target = "/user/pdf-solution/file/" + docId + "/" + java.net.URLEncoder.encode(mainName, java.nio.charset.StandardCharsets.UTF_8.name()).replace("+", "%20");
        response.sendRedirect(target);
    }
}
